package org.noote.libs.computervision.detection.blob;

import org.noote.libs.computervision.buffer.Buffer8888XRGB;
import org.noote.libs.computervision.buffer.Buffer8I;

public class SimpleColorDetection {

	public boolean detect(final Buffer8888XRGB xrgb, final int colorMaskMin, final int colorMaskMax, final boolean removeDetect, final boolean getMask, BlobSpace blob)
	{
		long acc_x = 0, acc_y = 0;
		long acc_count = 0;
		
		int max_x = 0, max_y = 0;
		
		int red_min=(colorMaskMin & 0xFF0000)>>16, green_min=(colorMaskMin & 0xFF00)>>8, blue_min=colorMaskMin & 0xFF;
		int red_max=(colorMaskMax & 0xFF0000)>>16, green_max=(colorMaskMax & 0xFF00)>>8, blue_max=colorMaskMax & 0xFF;
		
		int pixel, red, green, blue;
		for(int y=0; y<xrgb.getHeight(); y++)
		{
			for(int x=0; x<xrgb.getWidth(); x++)
			{
				pixel = xrgb.getPixel(x, y);
				
				red = (pixel & 0xFF0000)>>16;
				green = (pixel & 0xFF00)>>8;
				blue = pixel & 0xFF;
				
				if(red>red_max || red<red_min) continue;
				if(green>green_max || green<green_min) continue;
				if(blue>blue_max || blue<blue_min) continue;
				
				acc_x=x;
				acc_y=y;
				acc_count++;
				
				if(x>max_x) max_x = x;
				if(y>max_y) max_y = y;
				
				if(removeDetect)
				{
					xrgb.drawPixel(x, y, 0);
				}
			}
		}
		if(acc_count==0) return false;
		
		if(blob == null) blob = new BlobSpace();
		
		blob.acc = acc_count;
		
		blob.x = (int)(acc_x/acc_count);
		blob.y = (int)(acc_y/acc_count);
		blob.size_x = max_x-blob.x;
		blob.size_y = max_y-blob.y;
		
		blob.label = 1;
		
		if(getMask)
		{
			extractMaskFrom(blob, colorMaskMin, colorMaskMax, xrgb);
		}
		
		return true;
	}

	private boolean extractMaskFrom(BlobSpace blob, final int colorMaskMin, final int colorMaskMax, final Buffer8888XRGB xrgb) {
		blob.mask = new Buffer8I();
		
		int red_min=(colorMaskMin & 0xFF0000)>>16, green_min=(colorMaskMin & 0xFF00)>>8, blue_min=colorMaskMin & 0xFF;
		int red_max=(colorMaskMax & 0xFF0000)>>16, green_max=(colorMaskMax & 0xFF00)>>8, blue_max=colorMaskMax & 0xFF;

		if(blob.mask.createBuffer(blob.size_x, blob.size_y))
		{
			int pixel, red, green, blue;
			
			blob.mask.fill(0);
			
			for(int y=0; y<blob.size_y; y++)
			{
				for(int x=0; x<blob.size_x; x++)
				{
					pixel = xrgb.getPixel(blob.x+x, blob.y+y);
					
					red = (pixel & 0xFF0000)>>16;
					green = (pixel & 0xFF00)>>8;
					blue = pixel & 0xFF;
					
					if(red>red_max || red<red_min) continue;
					if(green>green_max || green<green_min) continue;
					if(blue>blue_max || blue<blue_min) continue;
					
					blob.mask.drawPixel(blob.x+x, blob.y+y, 255);
				}
			}
			return true;
		}
		
		return false;
	}
}
